﻿<% include Includes/Header.inc %>
using System.Runtime.Serialization;
using PetaPoco;
<%
_out.targetFile =  util.format('%s/Bases/QueryService.Generator.cs', projectDirectory);
%>

namespace <%= rootNamespace %>.Bases
{
    /// <summary>
    /// 基于PetaPoco的查询服务。
    /// </summary>
    public class QueryService<T>
    {
        private string _connectionStringName;
        private string _connectionString;
        private string _providerName;
        private string _fromClause;

        /// <summary>
        /// 构造方法。
        /// </summary>
        public QueryService(string connectionStringName, string fromClause)
        {
            _connectionStringName = connectionStringName;
            _fromClause = fromClause;
        }

        /// <summary>
        /// 构造方法。
        /// </summary>
        public QueryService(string connectionString, string providerName, string fromClause)
        {
            _connectionString = connectionString;
            _providerName = providerName;
            _fromClause = fromClause;
        }

        /// <inheritdoc />
        public IEnumerable<T> Fetch(string whereClause, object[] whereClauseParams, string orderClause)
        {
            using (var db = CreateDatabase())
            {
                var sql = this.CreateSqlFormQuery(whereClause, whereClauseParams, orderClause);

                return db.Fetch<T>(sql);
            }
        }

        /// <inheritdoc />
        public T SingleOrDefault(string whereClause, object[] whereClauseParams, string orderClause)
        {
            using (var db = CreateDatabase())
            {
                var sql = this.CreateSqlFormQuery(whereClause, whereClauseParams, orderClause);

                return db.SingleOrDefault<T>(sql);
            }
        }

        private Database CreateDatabase()
        {
            if (_connectionStringName != null)
            {
                return new Database(_connectionStringName);
            }

            return new Database(_connectionString, _providerName);
        }

        private Sql CreateSqlFormQuery(string whereClause, object[] whereClauseParams, string orderClause)
        {
            var sql = Sql.Builder;


            sql.Select("*");

            sql.From(_fromClause);

            if (!string.IsNullOrWhiteSpace(whereClause))
            {
                sql.Where(whereClause, whereClauseParams);
            }

            if (!string.IsNullOrWhiteSpace(orderClause))
            {
                sql.OrderBy(orderClause);
            }

            return sql;
        }
    }
}
